process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // 关闭证书

let all = null;
const { exec } = require('child_process');
const https = require('https');

const findLeagueClientCommandLine = async () => {
  return new Promise((resolve, reject) => {
    exec('"C:\\Windows\\System32\\wbem\\wmic" PROCESS WHERE "name=\'LeagueClientUx.exe\'" GET commandline', (err, stdout) => {
      if (err) {
        reject(err);
      } else {
        all = stdout;
        resolve(stdout);
      }
    });
  });
};

const getRiotData = async (url) => {
  const token = all.match(/remoting-auth-token=(.*?)["'\s]/)[1]
  const port = all.match(/--app-port=(.*?)["'\s]/)[1]
  const auth = Buffer.from(`riot:${token}`).toString('base64');
  const headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': `Basic ${auth}`
  };
  const options = {
    hostname: '127.0.0.1',
    port: port,
    path: url,
    method: 'GET',
    headers: headers
  };
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        resolve(data);
      });
    });
    req.on('error', (error) => {
      reject(error);
    });
    req.end();
  });
};

const main = async () => {
  try {
    const leagueClientCommandline = await findLeagueClientCommandLine();
    console.log('LeagueClientUx.exe 命令行参数:', leagueClientCommandline);
    const currentUser = await getRiotData('/lol-summoner/v1/current-summoner');
    console.log('感谢使用本程序, AUTHOR: 司, 当前获取到的用户数据:', currentUser);
  } catch (error) {
    console.error('发生错误:', error);
  }
};

main();